package org.koin.hos.scope;

import ohos.aafwk.ability.Ability;
import org.koin.core.component.KoinScopeComponent;
import org.koin.core.error.NoScopeDefFoundException;
import org.koin.core.error.ScopeAlreadyCreatedException;
import org.koin.core.qualifier.TypeQualifier;
import org.koin.core.scope.Scope;
import org.koin.hos.ext.hos.ContextExt;

public class ServiceExt {

    /**
     * Provide Koin Scope tied to Ability
     */
    public static Scope serviceScope(Ability service) {
        Scope scope = ContextExt.getScopeOrNull(service);
        if (scope == null) {
            scope = createScope(service, null);
        }
        return scope;
    }

    /**
     * Create new scope
     */
    public static Scope createScope(Ability service, Object source) {
        String scopeId = KoinScopeComponent.getScopeId(service);
        TypeQualifier scopeName = KoinScopeComponent.getScopeName(service);
        try {
            return ContextExt.getKoin(service).createScope(scopeId, scopeName);
        } catch (ScopeAlreadyCreatedException e) {
            e.printStackTrace();
        } catch (NoScopeDefFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Scope getScopeOrNull(Ability service) {
        String scopeId = KoinScopeComponent.getScopeId(service);
        return ContextExt.getKoin(service).getScopeOrNull(scopeId);
    }
}
